package com.natasa.monitor.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Http工具类
 * @author jianfeihit
 *
 */
public class HTTPUtils {
    /**
     * GET方式请求--以字符串的形式返回
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String getResponseAsStringByGetMethod(String url) throws ClientProtocolException, IOException{
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = client.execute(httpget);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString(); 
    }
    
    /**
     * POST方式请求--以字符串的形式返回
     * @param url
     * @param para
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String getResponseAsStringByPostMethod(String url,Map<String,String> para) throws ClientProtocolException, IOException{
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        for(String key : para.keySet()){
            httppost.getParams().setParameter(key, para.get(key));
        }; 
        HttpResponse response = client.execute(httppost);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString(); 
    }
    
    public static int getStatusCode(String url) throws ClientProtocolException, IOException{
        HttpClient httpClient = new DefaultHttpClient();  
        HttpHead httpHead = new HttpHead(url);  
        HttpResponse response = httpClient.execute(httpHead);  
        return response.getStatusLine().getStatusCode();
    }
}
